package com.jdone.compus.controller;

import com.jdone.compus.dto.ApiResponse;
import com.jdone.compus.dto.RechargeRequest;
import com.jdone.compus.dto.RefundRequest;
import com.jdone.compus.enums.ConsumptionStatus;
import com.jdone.compus.model.StudentOrder;
import com.jdone.compus.service.PaymentNotificationService;
import com.jdone.compus.service.StudentOrderService;
import com.jdone.compus.utils.SignUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/proxy")
@Api(value = "热水系统接口文档", tags = "热水系统接口文档")
public class ShowerApiProxyController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private StudentOrderService studentOrderService;

    @Autowired
    private PaymentNotificationService paymentNotificationService;

    @Value("${project.mchId}")
    private String mchId;

    @Value("${project.api.url}")
    private String url;

    @Value("${project.mchKey}")
    private String key;


    @ApiOperation("通过手机号查询用户注册信息")
    @GetMapping("/queryUserInfo")
    public Map<String, Object> queryUserInfo(@RequestParam String telPhone) {
        // 构建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String formattedDate = now.format(formatter);

        // 构建请求参数
        Map<String, String> params = new HashMap<>();
        params.put("mchId", mchId);
        params.put("signType", "MD5");
        params.put("telPhone", telPhone);
        //  params.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
        params.put("timestamp", formattedDate);
        params.put("requestType", "1");


        String sign = SignUtil.generateSign(params, key);
        params.put("sign", sign);

        // 将参数转换为 MultiValueMap
        MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
        body.setAll(params);

        // 构建请求实体
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(body, headers);

        ResponseEntity<Map> response = restTemplate.exchange(url + "/user/info", HttpMethod.POST, requestEntity, Map.class);

        // 返回响应给前端
        return response.getBody();
    }

    @ApiOperation("通过手机号查询用户的充值记录")
    @GetMapping("/queryRechargeRecords")
    public Map<String, Object> queryRechargeRecords(@RequestParam String telPhone,
                                                    @RequestParam(defaultValue = "1") Integer pageNumber) {
        // 设置固定参数
        String signType = "MD5"; // 签名方式，固定为MD5

        // 构建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String formattedDate = now.format(formatter);

        // 构建请求参数
        Map<String, String> params = new HashMap<>();
        params.put("mchId", mchId);
        params.put("signType", signType);
        params.put("telPhone", telPhone);
        params.put("timestamp", formattedDate);
        params.put("pageNumber", String.valueOf(pageNumber));


        String sign = SignUtil.generateSign(params, key);
        params.put("sign", sign);

        // 将参数转换为 MultiValueMap
        MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
        body.setAll(params);

        // 构建请求实体
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(body, headers);

        ResponseEntity<Map> response = restTemplate.exchange(url + "recharge/user/list", HttpMethod.GET, requestEntity, Map.class);

        // 返回响应给前端
        return response.getBody();
    }


    @ApiOperation("手动充值")
    @PostMapping("/recharge")
    @Transactional
    public Map<String, Object> recharge(@RequestBody RechargeRequest request) {
        // 根据商户订单号查找StudentOrder对象
        Optional<StudentOrder> optionalOrder = studentOrderService.getOrderByBusinessOrderNo(request.getOutTradeNo());
        if (optionalOrder.isPresent()) {
            StudentOrder order = optionalOrder.get();

            // 在调用远程充值接口之前，将消费状态更新为CONSUMED
            studentOrderService.updateOrderStatus(order.getOrderId(), ConsumptionStatus.CONSUMED);
            int result = (int) (order.getOrderAmount() * 1000);


            // 调用远程充值服务
            Map<String, Object> response = paymentNotificationService.recharge(request.getTelPhone(), result, request.getOutTradeNo());

            // 检查返回的errorCode是否为0，判断充值是否成功
            int errorCode = (int) response.getOrDefault("errorCode", -1);
            if (errorCode != 0) {
                // 如果充值失败，将消费状态恢复为PENDING
                studentOrderService.updateOrderStatus(order.getOrderId(), ConsumptionStatus.PENDING);
            }

            // 无论成功或失败，返回接口的响应信息
            return response;
        } else {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("errorCode", "400");
            errorResponse.put("errorMessage", "未找到订单");
            return errorResponse;
        }
    }


}
